package com.libra.assemble.web.listener.jms;

import com.libra.assemble.xutil.email.AttachmentForm;
import com.libra.assemble.xutil.enums.MessageType;
import com.libra.assemble.xutil.thread.Threads;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import java.io.FileOutputStream;
import java.util.List;


/**
 * 消息的异步被动接收者.
 * <p/>
 * 使用Spring的MessageListenerContainer侦听消息并调用本Listener进行处理.
 */
public class NotifyMessageListener implements MessageListener {

    private static Logger logger = LoggerFactory.getLogger(NotifyMessageListener.class);


    /**
     * MessageListener回调函数.
     */
    @Override
    public void onMessage(Message message) {
        logger.info("接收消息");
        MapMessage mapMessage = (MapMessage) message;
        try {
            MessageType messageType = MessageType.valueOf(mapMessage.getString("messageType"));
            switch(messageType){
                case SAVE_ATTACHMENT:
                    logger.info("保存附件...");
                    List<String> lines = (List<String>) mapMessage.getObject("attachmentList");

                    IOUtils.writeLines(lines, null, new FileOutputStream("/Users/Libra/Documents/workspace/idea/assemble/target/test-classes/email/aa.jpg") );
                    //saveAttachment((List<AttachmentForm>) mapMessage.getObject("attachmentList"));
                    break;
                default:
                    Threads.sleep(1000);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 异步保存邮件附件
     * @param attachmentFormList
     */
    private void saveAttachment(List<AttachmentForm> attachmentFormList){
        logger.info("attachmentFormList.size:{}",attachmentFormList.size());
    }


}
